<template>
  <div>
    <el-upload
      ref="uploadRef"
      class="upload-demo"
      :limit="1"
      :headers="importHeaders"
      :action="`${BASEURL}${action}`"
      :on-success="handleSuccess"
      :on-exceed="handleExceed"
      :show-file-list="false"
      :on-change="handleChange">
      <el-button class="upload-button">{{ fileUrl ? '替换文件' : '上传文件' }}</el-button>
    </el-upload>
    <span class="tips">{{tips}}</span>
    <div style="width: 100%;">
      <el-button type="text" v-show="fileUrl">
        <a :href="fileUrl" target="_blank" class="download" rel="noopener noreferrer">
          {{fileTypeName}}-{{ queryLastName(fileUrl) }}</a>
      </el-button>
      <el-input v-model="fileUrl" v-show="false" />
    </div>
  </div>
</template>

<script>
import { ref, onMounted, defineComponent, computed } from "vue";
import { ElMessage } from "element-plus";
import { useStore } from "vuex";
import { queryLastName } from "@/utils/index.js";

export default defineComponent({
  props: {
    modelValue: {
      type: [String]
    },
    action: {
      type: String,
      default: '/attachment/upload'
    },
    fileTypeName: {
      type: String,
      default: '接口文档'
    },
    tips: {
      type: String,
      default: '上传应用方提供的接口文档作为留档'
    }
  },
  setup(props, {emit}) {
    const store = useStore();
    const fileUrl = computed({
      get: () => props.modelValue,
      set: (val) => emit("update:modelValue", val)
    })
    // 上传相关参数
    const uploadRef = ref(null)
    const BASEURL = ref(import.meta.env.VITE_APP_BASE_API);
    const importHeaders = ref({
      Authorization: store.getters.token,
      ORG: store.getters.currentOrgId,
    });
    // 上传成功
    const handleSuccess = ({ status, data, message }) => {
      if (status === 200) {
        // 请求成功 上传成功
        const url = data.fileUrl?data.fileUrl:data
        emit('update:modelValue', url)
        ElMessage.success("上传成功");
      } else {
        // 请求成功 上传失败
        ElMessage.error(message);
      }
    };

    // 覆盖上传
    const handleExceed = (files) => {
      console.log('覆盖上传')
      uploadRef.value.clearFiles()
      const file = files[0]   
      uploadRef.value.handleStart(file)
      uploadRef.value.submit()
    }
    const handleChange = (file,files) => {
      console.log('文件变化')
      console.log(file)
    }
    return {
      fileUrl,
      uploadRef,
      BASEURL,
      importHeaders,
      queryLastName,
      handleSuccess,
      handleExceed,
      handleChange,
    };
  },
});
</script>

<style lang="scss" scoped>
.tips {

font-size: 14px;
font-family: PingFangSC-Regular, PingFang SC;
font-weight: 400;
color: #858C99;
}
.upload-button {
  border-radius: 2px !important;
  color: rgba(46, 105, 235, 1);
  margin-right: 10px;
  border: 1px dashed rgba(46, 105, 235, 1);
}
</style>
